# -*- coding: utf-8 -*-
import paramiko
import threading
import os
from logger import loggerDefine


class RemoteCmd:
    try:
        # 定义通用日志
        logcmd = loggerDefine("RemoteCmd", "RemoteCmd.log")
    except:
        pass

    def ssh2(self, ip, port, username, passwd, cmd):
        """
        ssh远程执行命令代码
        ip:主机IP地址
        username：登录用户名 最好是root
        passwd:登录密码
        cmd:远程执行命令列表,如[cmd1,cmd2,cmd3...]
       """

        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            #  默认用22端口
            ssh.connect(ip, port, username, passwd, timeout=5)
            for m in cmd:
                self.logcmd.info(ip + "  执行-->:  " + m + "  命令")
                stdin, stdout, stderr = ssh.exec_command(m)
                stdin.write("Y")  # 简单交互，输入 ‘Y’
                out = stdout.readlines()
                # 输出日志
                for o in out:
                    self.logcmd.info(ip + "执行命令:" + m + "  执行结果-->:" + o)

            self.logcmd.info('%s\t远程ssh命令执行完成\n' % (ip))
            # 关闭ssh
            ssh.close()
        except:
            self.logcmd.error('%s\t远程ssh失败\n' % (ip))

    def readLinuxlist(self, filenamepath=None):
        """
         filename:文件名
        """
        if filenamepath:
            filename = filenamepath
        else:
            root_dir = os.path.abspath('.')  # 获取当前路径
            filename = os.path.join(root_dir, "config/linux_hosts.list")

        with open(filename, encoding="utf8") as f:
            for line in f:
                # 不以注释开头且不是空行
                if not line.startswith('#') and not line.isspace():
                    """ 
                    去掉换行符并分割字符串,分割5次(返回次数+1)
                     格式:主机IP地址 端口 用户名 密码 命令集合(cmd1,cmd2,cmd3...)
                            ip port username passwd cmd...
                    """
                    # print(line.strip('\n').split(' ', 4))

                    testlist = line.strip('\n').split(' ', 4)
                    #   格式:主机IP地址 端口 用户名 密码 命令集合(cmd1,cmd2,cmd3...)
                    #  ip port username passwd cmd...
                    ip = testlist[0]
                    port = testlist[1]
                    username = testlist[2]
                    passwd = testlist[3]
                    cmds = testlist[4].split(",")  # 命令列表进行分割

                    self.logcmd.info("远程服务器ssh  " + ip + ":" + port + "  执行命令列表为-->: " + str(cmds))
                    """启用多线程"""
                    a = threading.Thread(target=self.ssh2, args=(ip, port, username, passwd, cmds))
                    a.start()
                else:
                    self.logcmd.error("配置文件-->: "+filename+" 远程主机列表为空，不能执行远程命令")

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    asu = RemoteCmd()
    asu.readLinuxlist()
